$(document).ready(function() {
	var DestoutObj="";
	//var label = new Label();
    var VAL ={
        NORMAL     : "0000000"  ,
        T_XPWHSOPE : "XPWHSOPE" ,
        T_XPAPLYSO : "XPAPLYSO" ,
        T_XPBISMTR : "XPBISMTR" ,
        T_XPAPLYWO : "XPAPLYWO" ,
        T_XPINQWOR : "XPINQWOR" ,
        isModify   : false,
        modifyRowId : -1,
        EVT_USER   : $("#userId").text(),
        woMtrl_Prod_ID : "",
        woMdl_ID : "",
        woCus_Info_Fst : ""	,
        woCus_Info_Snd : ""
    };
    var domObj = {
			$window : $(window),
			$panelMaterialDeliveryInfoDiv : $("#panelMaterialDeliveryInfoDiv"),
			$panelMaterialDeliveryInfoGrd : $("#panelMaterialDeliveryInfoGrd"),
			$bindWoDialog_woGrd : $("#bindWoDialog_woGrd")
	};
	var baseFnc = {
			replaceSpace:function(str){
				if(!str){
					return str;
				}
				return str.replace(/[ ]/g,"@");	
			},
			returnSpace:function(str){
				if(!str){
					return str;
				}
				return str.replace(/[@]/g," ");
			}
	};
    /**
     * All controls's jquery object/text
     * @type {Object}
     */
    var controlsQuery = {
        W                        : $(window)                      ,
        vdrIDSelect              : $("#vdrIDSelect")              ,
        mtrlTypeSelect           : $("#mtrlTypeSelect")           ,
        destShopSelect           : $("#destShopSelect")           ,
        woIdSelect               : $("#woIdSelect")               ,//change input to select
        stdThicknessTxt          : $("#stdThicknessTxt")          ,
        rawBoxIDInput            : $("#rawBoxIDInput")            ,
        rawBoxStdQtyInput        : $("#rawBoxStdQtyInput")        ,
        rawCountInput            : $("#rawCountInput")            ,
        thicknessTxt             : $("#thicknessTxt")            ,
        rawWeightInput           : $("#rawWeightInput")           ,
        woCountInput             : $("#woCountInput") ,
        getCountInput            : $("#getCountInput") ,
        woBoxTotalCntInput       : $("#woBoxTotalCntInput") ,
        prtBoxRuleInput          : $("#prtBoxRuleInput"),
        mtrlIdInput              : $("#mtrlIdInput"),
        hdIdInput                : $("#hdIdInput"),
        mtrlBoxInput             : $("#mtrlBoxInput"),
        mainGrd   :{
            grdId     : $("#panelMaterialDeliveryInfoGrd")   ,
            grdPgText : "#panelMaterialDeliveryInfoPg"       ,
            fatherDiv : $("#panelMaterialDeliveryInfoDiv")
        }
    };

    /**
     * All button's jquery object
     * @type {Object}
     */
    var btnQuery = {
        f1 : $("#f1_btn"),
        f4 : $("#f4_btn"),
        f5 : $("#f5_btn"),
        f8 : $("#f8_btn"),
        f9 : $("#f9_btn"),
        f11: $("#f11_bind_btn"),
        addNewMtrlType : $("#addNewMtrlTypeBtn"),
        autoCreateBox  : $("#autoCreateBoxBtn"),
        $importTmCusPrdBtn :$("#importTmCusPrdBtn")
       // $importCusPrdBtn : $("#importCusPrdBtn")
    };

    /**
     * All tool functions
     * @type {Object}
     */
    var toolFunc = {
        clearInput : function(){
            controlsQuery.rawBoxIDInput.val("");
            controlsQuery.mtrlBoxInput.val("");
            controlsQuery.rawBoxStdQtyInput.val("");
            controlsQuery.rawCountInput.val("");
            controlsQuery.rawWeightInput.val("");
            controlsQuery.woCountInput.val("");
            controlsQuery.getCountInput.val("0");

            controlsQuery.stdThicknessTxt.val("");
            controlsQuery.thicknessTxt.val("");

            //UnLock item can't be modify
            controlsQuery.vdrIDSelect.removeAttr("disabled","");
            controlsQuery.rawBoxIDInput.removeAttr("disabled","").removeClass("disabled");
            controlsQuery.woIdSelect.removeAttr("disabled","").removeClass("disabled");
        },
        /**
         * 筛选出用户可以操作的仓位 By CMJ
         */
        setDestShopSel : function(){
        	var inObj;
        	var data_ext = "'C','D'";
        	var iary={
        		data_cate : 'DEST',
        		data_ext  : data_ext,
        		user_id   : VAL.EVT_USER
        	};
        	inObj = {
			   trx_id     : 'XPLSTDAT' ,
	           action_flg : 'F'        ,
	           iary       : iary
        	};
        	DestoutObj = comTrxSubSendPostJson(inObj);
        	if(DestoutObj.rtn_code == VAL.NORMAL){
        		_setSelectDate(DestoutObj.tbl_cnt,DestoutObj.oary,"data_id","data_desc","#destShopSelect",true);
        	}
        },
        setRowDateForUpdate : function(rowid){
            var rowData = controlsQuery.mainGrd.grdId.getRowData(rowid);
            var box_id = rowData['box_id'];
            var vdr_id = rowData['vdr_id'];
            var mtrl_type = rowData['mtrl_type'];
            var count = rowData['count'];
            var weight = rowData['weight'];
            var dest_shop = rowData['dest_shop'];
            var wo_id = rowData['wo_id'];
            var box_std_qty = rowData['box_std_qty'];

            //Set select row value
            controlsQuery.vdrIDSelect.val(vdr_id);
            controlsQuery.mtrlTypeSelect.val(baseFnc.replaceSpace(mtrl_type));
            controlsQuery.destShopSelect.val(dest_shop).trigger("change");;

            controlsQuery.rawBoxIDInput.val(box_id);
            controlsQuery.rawCountInput.val(count);
            controlsQuery.rawWeightInput.val(weight);
            controlsQuery.woIdSelect.val(wo_id).trigger("change");;
            controlsQuery.rawBoxStdQtyInput.val(box_std_qty);
            //Lock item can't be modify
            controlsQuery.vdrIDSelect.attr("disabled","");
            controlsQuery.rawBoxIDInput.attr("disabled","").addClass("disabled");
            controlsQuery.woIdSelect.attr("disabled","").addClass("disabled");

            //Hide buttons not need
            btnQuery.f1.hide();
            btnQuery.f4.hide();
            btnQuery.f8.hide();
            btnQuery.f11.hide();
            //Show f9: cancel modify
            btnQuery.f9.show();

            VAL.isModify = true;
            VAL.modifyRowId = rowid;
        },
        getWoStdFromThickness : function(){
            var wo_id,
                inObj,
                outObj,
                from_thickness = 0;

            wo_id = controlsQuery.woIdSelect.val().trim();
            if(!wo_id){
                console.warn("wo_id [%s] is null!", wo_id);
                return 0;
            }

            inObj = {
                trx_id      : VAL.T_XPAPLYWO,
                action_flg  : 'Q'           ,
                tbl_cnt     : 1             ,
                iary : {
                    wo_id     : wo_id,
                    mtrl_cate : "SHMT"
                }
            };
            outObj = comTrxSubSendPostJson(inObj);
            if (outObj.rtn_code == VAL.NORMAL) {
                if( parseInt( outObj.tbl_cnt,10 ) >0 ){
                    if( outObj.hasOwnProperty("oary")){
                    	VAL.woMtrl_Prod_ID = outObj.oary.mtrl_prod_id_fk;
                        if( outObj.oary.hasOwnProperty("from_thickness")){
                            from_thickness = outObj.oary.from_thickness;
                            return from_thickness;
                        }
                    }
                }
            }
            return 0;
        },
        syncWoSumInfo : function(wo_id){
            var inObj,
                outObj,
                so_pln_prd_qty;

            if(!wo_id){
                console.warn("wo_id [%s] is null!", wo_id);
                return false;
            }

            inObj = {
                trx_id      : VAL.T_XPINQWOR,
                action_flg  : 'S'           ,
                worder_id   : wo_id
            };
            outObj = comTrxSubSendPostJson(inObj);
            if (outObj.rtn_code == VAL.NORMAL) {
            	so_pln_prd_qty = outObj.out1.so_tb == undefined ? "" : outObj.out1.so_tb.pln_prd_qty;
            	controlsQuery.getCountInput.val(so_pln_prd_qty);
            	controlsQuery.woCountInput.val(outObj.out1.wo_tb.pln_prd_qty);
            }
            return true;
        },
        iniWoIdSelect : function(){
            var inObj,
                outObj;
            var vdr_id = $.trim(controlsQuery.vdrIDSelect.val()); 
            var mtrl_type = baseFnc.returnSpace( $.trim(controlsQuery.mtrlTypeSelect.val()));
            inObj = {
                    trx_id      : VAL.T_XPAPLYWO,
                    action_flg  : 'Q'           ,
            		iary       : {
            			wo_stat: "WAIT"
            		}

                };

            if( vdr_id ){
        		inObj.iary.cus_id = vdr_id;        		
            }
            if(mtrl_type ){
        		inObj.iary.mtrl_prod_id_fk = mtrl_type;        		
            }

            outObj = comTrxSubSendPostJson(inObj);
            if (outObj.rtn_code == VAL.NORMAL) {
                _setSelectDate(outObj.tbl_cnt, outObj.oary, "wo_id", "wo_id", "#woIdSelect", true);
            }
        },
        getWoInfo : function(){
            var inObj,
                outObj;
            var wo_id = $.trim(controlsQuery.woIdSelect.val()); 
            var mtrl_type = baseFnc.returnSpace( $.trim(controlsQuery.mtrlTypeSelect.val()));
            inObj = {
                    trx_id      : VAL.T_XPAPLYWO,
                    action_flg  : 'Q'           ,
            		iary       : {
            			wo_id: wo_id
            		}

                };

            outObj = comTrxSubSendPostJson(inObj);
            if (outObj.rtn_code == VAL.NORMAL) {
                VAL.woMdl_ID = outObj.oary.mdl_id;
                VAL.woCus_Info_Fst = outObj.oary.cus_info_fst;
                VAL.woMtrl_Prod_ID = outObj.oary.mtrl_prod_id_fk;
                VAL.woCus_Info_Snd = outObj.oary.cus_info_snd;
            }
        }
    };

    /**
     * All button click function
     * @type {Object}
     */
    var btnFunc = {
        //Query
        f1_func : function(){
            var vdr_id = $.trim(controlsQuery.vdrIDSelect.val());
            var box_id = $.trim(controlsQuery.rawBoxIDInput.val());
            var dest_shop = $.trim(controlsQuery.destShopSelect.val());
            var wo_id = $.trim(controlsQuery.woIdSelect.val());

            var iary = {};
            if(vdr_id){
                iary.vdr_id = vdr_id;
            }else{
                showErrorDialog("","请选择客户代码！");
                return false;
            }
            /**
             * 判断用户是否有可以操作的仓位 By CMJ
             */
            if(DestoutObj.tbl_cnt == 0){
            	showErrorDialog("","此用户没有可以操作的仓位！");
                return false;
            }
            if(box_id){
                iary.box_id = box_id;
            }else{
                if(dest_shop){
                    iary.dest_shop = "'"+dest_shop+"'";
                }else{
                	/**
                	 * 增加筛选条件：仓位 By CMJ
                	 */
                	for(var i=0;i<DestoutObj.tbl_cnt;i++){
                		var oary = DestoutObj.tbl_cnt>1 ? DestoutObj.oary[i] : DestoutObj.oary;
                		if(i==0){
                			dest_shop = "'"+oary.data_id+"'";
                		}else{
                			dest_shop +=",'"+oary.data_id+"'";
                		}
                	}
                	iary.dest_shop = dest_shop;
                }
                if(wo_id){
                    iary.wo_id = wo_id;
                }else{
                	showErrorDialog("","请选择内部订单号！");
	                return false;
	            }
            	
            }

            var inTrxObj = {
                trx_id: VAL.T_XPWHSOPE,
                action_flg : 'Q',
                box_stat   :'WAIT',
                iary       : iary
            };
            var outTrxObj = comTrxSubSendPostJson(inTrxObj);
            if(outTrxObj.rtn_code == VAL.NORMAL) {
            	if(outTrxObj.box_cnt == 0){//查询不到，增加提示，并清空grid.
            		controlsQuery.mainGrd.grdId.jqGrid("clearGridData");
            		showErrorDialog("","查询不到来料箱号！");
	                return false;
            	}
            	/**
            	 * 单独输入箱子查询信息时，也要检查用户对仓位的权限。By CMJ
            	 */
            	if(outTrxObj.box_cnt>0){
            		if(box_id){
                		for(var j=0;j<DestoutObj.tbl_cnt;j++){
                    		var oary = DestoutObj.tbl_cnt>1 ? DestoutObj.oary[j] : DestoutObj.oary;
                    		if($.trim(oary.data_id)== $.trim(outTrxObj.oary.dest_shop)){
                    			break;
                    		}
                    	}
                		if(DestoutObj.tbl_cnt ==0||j>=DestoutObj.tbl_cnt){
                			showErrorDialog("","此用户没有权限操作这个箱子，箱子的仓位为["+outTrxObj.oary.dest_shop+"].");
        	                return false;
                		}
                	}
            		/**
                	 * 获取仓位描述
                	 * @author CMJ
                	 */
                	for(var i=0;i<outTrxObj.box_cnt;i++){
                		var oary = outTrxObj.box_cnt>1 ? outTrxObj.oary[i] : outTrxObj.oary;
                		var desc = DestTrans.getTran("'C','D'",oary.dest_shop);
                		oary.dest_shop_dsc = desc==undefined ? oary.dest_shop : desc;
                	}
                	setGridInfo(outTrxObj.oary,"#panelMaterialDeliveryInfoGrd");
            	}
            }
        },
        //Delete
        f4_func : function(){
            var delCntSum = 0,
                iRow,
                selectRowIds,
                selectRowIdsLen,
                selectRow,
                inTrxObj,
                outTrxObj,
                selecBoxIDs = [];

            selectRowIds = controlsQuery.mainGrd.grdId.jqGrid('getGridParam','selarrrow');
            selectRowIdsLen = selectRowIds.length;
            if(selectRowIdsLen <= 0){
                showErrorDialog("","请选择要删除的记录！");
                return false;
            }

            for( iRow = 0; iRow<selectRowIdsLen; iRow++){
                selectRow = controlsQuery.mainGrd.grdId.jqGrid("getRowData", selectRowIds[iRow]);
                selecBoxIDs[iRow] = {
                    vdr_id : selectRow['vdr_id'],
                    box_id : selectRow['box_id'],
                    mtrl_type : selectRow['mtrl_type'],
                    wo_id : selectRow['wo_id'],
                    diffCnt : -parseInt(selectRow['count'], 10)
                };

                delCntSum += parseInt(selectRow['count'], 10);
            }

            inTrxObj = {
                trx_id     : VAL.T_XPWHSOPE,
                action_flg : 'D',
                evt_user   : VAL.EVT_USER,
                box_cnt    : selectRowIdsLen,
                iary       : selecBoxIDs
            };
            outTrxObj = comTrxSubSendPostJson(inTrxObj);
            if(outTrxObj.rtn_code == VAL.NORMAL) {
                for( iRow = selectRowIdsLen-1; iRow>=0; iRow-- ){
                    //When I delete one selected row from grid,  array selectRowIds will auto delete this item.
                    //So must fetch iRow from array length to 0
                    controlsQuery.mainGrd.grdId.jqGrid('delRowData', selectRowIds[iRow]);
                }

                //update count
                toolFunc.syncWoSumInfo($.trim(controlsQuery.woIdSelect.val()));
                showSuccessDialog("删除成功！");
            }

            return true;
        },
        //Update
        f5_func : function(){
            var crGrid,
                ids,
                idLen,
                diffCnt,
                inTrxObj,
                outTrxObj;

            crGrid = controlsQuery.mainGrd.grdId;
            if(false === VAL.isModify){
                ids = crGrid.jqGrid('getGridParam','selarrrow');
                idLen = ids.length;
                if(0 === idLen){
                    showErrorDialog("","请勾选需要更新的行！");
                    return false;
                }else if(1 !== idLen){
                    showErrorDialog("","请勾选1行！");
                    return false;
                }else{
                    toolFunc.setRowDateForUpdate(ids[0]);
                }

                return true;
            }

            var rowData = crGrid.getRowData(VAL.modifyRowId);

            var vdr_id = $.trim(controlsQuery.vdrIDSelect.val());
            var mtrl_type = baseFnc.returnSpace( $.trim(controlsQuery.mtrlTypeSelect.val()));
            var dest_shop = $.trim(controlsQuery.destShopSelect.val());
            var wo_id = $.trim(controlsQuery.woIdSelect.val());
            var box_id = $.trim(controlsQuery.rawBoxIDInput.val());
            var raw_count = $.trim(controlsQuery.rawCountInput.val());
            var raw_weight = $.trim(controlsQuery.rawWeightInput.val());
            var box_std_qty = $.trim(controlsQuery.rawBoxStdQtyInput.val());
            
            if( !mtrl_type ){showErrorDialog("","请选择来料型号！"); return false;}
            if( !dest_shop ){showErrorDialog("","请选择仓位！"); return false;}
            if( !wo_id ){showErrorDialog("","请选择内部订单号！"); return false;}
            if( !box_id ){showErrorDialog("","请输入来料箱号！"); return false;}
            if( !raw_count ){showErrorDialog("","请输入数量！"); return false;}
            
            if( !box_std_qty){showErrorDialog("","请输入箱子的子格位数！"); return false;}
            box_std_qty = parseInt(box_std_qty, 10);
            if(isNaN(box_std_qty)){
                showErrorDialog("","请输入正确的子格位数！");
                return false;
            }
            if(box_std_qty <=0){
                showErrorDialog("","子格位数不能为0！");
                return false;
            }
            
            raw_count = parseInt(raw_count, 10);
            if(isNaN(raw_count)){
                showErrorDialog("","请输入正确的数量！");
                return false;
            }
            if(raw_count <=0){
                showErrorDialog("","数量不能为0！");
                return false;
            }

            if(box_std_qty < raw_count){
                showErrorDialog("","子格位数不能小于箱子中产品数量！");
                return false;
            }
            
            if(raw_weight){ //有输入才检查
                if( parseFloat(raw_weight) >= 0) {
                    raw_weight = parseFloat(raw_weight);
                }else{
                    showErrorDialog("","来料毛重数值不正确，请输入正确数字！");
                    return false;
                }
            }

            diffCnt = parseInt(raw_count) - parseInt(rowData['count'], 10);

            inTrxObj = {
                trx_id     : VAL.T_XPWHSOPE,
                action_flg : 'U',
                evt_user   : VAL.EVT_USER,
                box_cnt    : 1 ,
                wo_id      : wo_id,
                iary :  {
                    vdr_id    : vdr_id,
                    box_id    : box_id,
                    mtrl_type : mtrl_type,
                    dest_shop : dest_shop,
                    wo_id     : wo_id,
                    diffCnt   : diffCnt,
                    box_std_qty : box_std_qty,
                    weight    : raw_weight || 0
                }
            };

            outTrxObj = comTrxSubSendPostJson(inTrxObj);
            if(outTrxObj.rtn_code == VAL.NORMAL) {
                rowData['vdr_id'] = vdr_id;
                rowData['mtrl_type'] = mtrl_type;
                rowData['dest_shop'] = dest_shop;
                rowData['count'] = raw_count;
                rowData['weight'] = raw_weight || 0;
                rowData['box_std_qty'] = box_std_qty;
                controlsQuery.mainGrd.grdId.jqGrid('setRowData', VAL.modifyRowId, rowData);

                //update count
                if(0 !== diffCnt){
                    toolFunc.syncWoSumInfo(wo_id);
                }

                showSuccessDialog("修改成功！");
                this.f9_func();
            }

            return true;
        },
        //Add
        f8_func : function(){
            'use strict';
            var inTrxObj,
                box_id,
                stdFromThickness,
                box_std_qty,
                inWoTrxObj,
                outWoTrxObj,
                wo_pln_prd_qty,
                wo_rsv_pln_prd_qty,
                wo_rsv_dps_qty,
                wo_rsv_snd_dps_qty,
                wo_rsv_trd_dps_qty,
//                wo_act_dps_qty,
//                wo_act_snd_dps_qty,
//                wo_act_trd_dps_qty,
                lchkflg;

            var vdr_id = $.trim(controlsQuery.vdrIDSelect.val());
            var mtrl_type = baseFnc.returnSpace($.trim(controlsQuery.mtrlTypeSelect.val()));
            var dest_shop = $.trim(controlsQuery.destShopSelect.val());
            var wo_id = $.trim(controlsQuery.woIdSelect.val());
            var raw_count = $.trim(controlsQuery.rawCountInput.val());
            var raw_weight = $.trim(controlsQuery.rawWeightInput.val());
            var thickness = $.trim(controlsQuery.thicknessTxt.val());
            var vdr_box_id =  $.trim(controlsQuery.mtrlBoxInput.val());
            box_std_qty =  $.trim(controlsQuery.rawBoxStdQtyInput.val());

            if( !vdr_id ){showErrorDialog("","请选择客户代码！"); return false;}
            if( !mtrl_type ){showErrorDialog("","请选择来料型号！"); return false;}
            if( !dest_shop ){showErrorDialog("","请选择仓位！"); return false;}
            if( !wo_id ){showErrorDialog("","请选择内部订单号！"); return false;}
            
            box_id = $.trim(controlsQuery.rawBoxIDInput.val());
            if( !box_id ){
            	btnFunc.autoCreateBoxFunc();
            	box_id = $.trim(controlsQuery.rawBoxIDInput.val());
            }
            if (!vdr_box_id){
            	vdr_box_id = box_id;
            }
            
            if( !box_std_qty){showErrorDialog("","请输入箱子的子格位数！"); return false;}
            box_std_qty = parseInt(box_std_qty, 10);
            if(isNaN(box_std_qty)){
                showErrorDialog("","请输入正确的子格位数！");
                return false;
            }
            if(box_std_qty <=0){
                showErrorDialog("","子格位数不能为0！");
                return false;
            }
            if( !raw_count ){showErrorDialog("","请输入数量！"); return false;}
            raw_count = parseInt(raw_count, 10);
            if(isNaN(raw_count)){
                showErrorDialog("","请输入正确的数量！");
                return false;
            }
            if(raw_count <=0){
                showErrorDialog("","数量不能为0！");
                return false;
            }

            if(box_std_qty < raw_count){
                showErrorDialog("","子格位数不能小于箱子中产品数量！");
                return false;
            }
            if(raw_weight){ //有输入才检查
                if( parseFloat(raw_weight) >= 0) {
                    raw_weight = parseFloat(raw_weight);
                }else{
                    showErrorDialog("","来料毛重数值不正确，请输入正确数字！");
                    return false;
                }
            }

            stdFromThickness = toolFunc.getWoStdFromThickness();
            stdFromThickness = parseFloat(stdFromThickness);
            controlsQuery.stdThicknessTxt.val(stdFromThickness);

            if (mtrl_type != VAL.woMtrl_Prod_ID){showErrorDialog("","当前所选来料型号["+mtrl_type+"]和内部订单来料型号["+VAL.woMtrl_Prod_ID+"]不符"); return false;}

            if(thickness){ //有输入才检查
                if( parseFloat(thickness) >= 0) {
                    thickness = parseFloat(thickness);
                }else{
                    showErrorDialog("","产品厚度数值不正确，请输入正确数字！");
                    return false;
                }

                if( 0 != stdFromThickness &&
                    thickness != stdFromThickness){
                    showErrorDialog("","内部订单绑定的产品厚度["+ stdFromThickness +"]和输入值["+ thickness +"]不符！！");
                    return false;
                }
            }

            inTrxObj = {
                trx_id     : VAL.T_XPWHSOPE,
                action_flg : 'A',
                evt_user   : VAL.EVT_USER,
                box_cnt    : 1 ,
                wo_id      : wo_id,
                iary :  {
                    vdr_id    : vdr_id,
                    box_id    : box_id,
                    mtrl_type : mtrl_type,
                    dest_shop : dest_shop,
                    wo_id     : wo_id,
                    diffCnt   : raw_count,
                    vdr_box_id:vdr_box_id,
                    box_std_qty : box_std_qty,
                    weight    : raw_weight || 0
                }
            };

            //Query WO info
            inWoTrxObj = {
                trx_id      : VAL.T_XPAPLYWO,
                action_flg  : 'Q'           ,
                tbl_cnt     : 1             ,
                iary : {
                    wo_id     : wo_id
                }
            };
            outWoTrxObj = comTrxSubSendPostJson(inWoTrxObj);
            if (outWoTrxObj.rtn_code == VAL.NORMAL) {
                if( parseInt( outWoTrxObj.tbl_cnt,10 ) >0 ){
                    if( outWoTrxObj.hasOwnProperty("oary")){
                    	lchkflg = 0;
                    	wo_rsv_pln_prd_qty = parseInt(outWoTrxObj.oary.rsv_pln_prd_qty, 10);
                    	wo_pln_prd_qty = parseInt(outWoTrxObj.oary.pln_prd_qty, 10);
                        wo_rsv_dps_qty = parseInt(outWoTrxObj.oary.rsv_dps_qty, 10);
                        wo_rsv_snd_dps_qty = parseInt(outWoTrxObj.oary.rsv_snd_dps_qty, 10);
                        wo_rsv_trd_dps_qty = parseInt(outWoTrxObj.oary.rsv_trd_dps_qty, 10);
//                        wo_act_dps_qty = parseInt(outWoTrxObj.oary.act_dps_qty, 10);
//                        wo_act_snd_dps_qty = parseInt(outWoTrxObj.oary.act_snd_dps_qty, 10);
//                        wo_act_trd_dps_qty = parseInt(outWoTrxObj.oary.act_trd_dps_qty, 10);
                        
                        
                        if ( parseInt((wo_pln_prd_qty + parseInt(raw_count,10)),10) > wo_rsv_pln_prd_qty ) {
                        	if (wo_rsv_dps_qty == wo_rsv_pln_prd_qty) {
                            	lchkflg = 1;
                        	}else if (wo_rsv_dps_qty == wo_rsv_snd_dps_qty){
                            	lchkflg = 1;
                        	}else if (wo_rsv_dps_qty == wo_rsv_trd_dps_qty){
                            	lchkflg = 1;
                        	}
                        } 
                        
//                        if(wo_act_dps_qty + raw_count > wo_rsv_dps_qty && wo_rsv_dps_qty != 0){
//                        	lchkflg = 1;
//                        	wo_pln_prd_qty = wo_act_dps_qty;
//                            wo_rsv_pln_prd_qty = wo_rsv_dps_qty;                        	
//                        }else if(wo_act_snd_dps_qty + raw_count > wo_rsv_snd_dps_qty && wo_rsv_snd_dps_qty != 0){
//                        	lchkflg = 1;
//                        	wo_pln_prd_qty = wo_act_snd_dps_qty;
//                            wo_rsv_pln_prd_qty = wo_rsv_snd_dps_qty;                        	
//                        }else if(wo_act_trd_dps_qty + raw_count > wo_rsv_trd_dps_qty && wo_rsv_trd_dps_qty != 0){
//                        	lchkflg = 1;
//                        	wo_pln_prd_qty = wo_act_trd_dps_qty;
//                            wo_rsv_pln_prd_qty = wo_rsv_trd_dps_qty;                        	
//                        }
                        if(lchkflg == 1){
//                            wo_pln_prd_qty += raw_count;
                            showWarnningDialog({
                                errMsg  : '内部订单[' + wo_id +
                                    ']此笔来料后实际来料数量[' + wo_pln_prd_qty + '+' + parseInt(raw_count,10) +
                                    ']大于计划来料数量[' + wo_rsv_pln_prd_qty + '],' +
                                    '系统将根据计划交期的优先级进行计划的实际来料数量绑定，是否执行?',
                                callbackFn : function(data) {
                                    if(data.result === true){
                                        //over
                                        inTrxObj.setDpsCntOverPln = 'Y';
                                    }else{
//                                        inTrxObj.setDpsCntKeepPlnCnt = wo_rsv_pln_prd_qty - (wo_pln_prd_qty - raw_count);
                                    }
                                    btnFunc.f8_func_real_send(inTrxObj);

                                    //Set add up count
                                    toolFunc.syncWoSumInfo(wo_id);

                                    //Clear input
                                    controlsQuery.rawBoxIDInput.val("");
                                    controlsQuery.rawBoxIDInput.focus();
                                    controlsQuery.mtrlBoxInput.val("");
                                }
                            });
                        }else{
                            btnFunc.f8_func_real_send(inTrxObj);

                            //Set add up count
                            toolFunc.syncWoSumInfo(wo_id);

                            //Clear input
                            controlsQuery.rawBoxIDInput.val("");
                            controlsQuery.rawBoxIDInput.focus();
                            controlsQuery.mtrlBoxInput.val("");
                        }
                    }
                }
            }//End of wo query

            return true;
        },
        f8_func_real_send : function(inTrxObj){
            'use strict';
            var outTrxObj,
                rowObj;

            outTrxObj = comTrxSubSendPostJson(inTrxObj);
            if(outTrxObj.rtn_code == VAL.NORMAL) {
                rowObj = {
                    box_id        : outTrxObj.oary.box_id       ,
                    vdr_id        : outTrxObj.oary.vdr_id       ,
                    mtrl_type     : outTrxObj.oary.mtrl_type    ,
                    dest_shop     : outTrxObj.oary.dest_shop    ,
                    dest_shop_dsc : outTrxObj.oary.dest_shop    ,
                    wo_id         : outTrxObj.oary.wo_id        ,
                    count         : outTrxObj.oary.count        ,
                    weight        : outTrxObj.oary.weight       ,
                    ppbox_stat    : outTrxObj.oary.ppbox_stat   ,
                    rcv_user      : outTrxObj.oary.rcv_user     ,
                    rcv_timestamp : outTrxObj.oary.rcv_timestamp,
                    box_std_qty   : outTrxObj.oary.box_std_qty
                };
                /*获取仓位描述*/
                var desc = DestTrans.getTran("'C','D'",rowObj.dest_shop);
                rowObj.dest_shop_dsc = desc==undefined ? rowObj.dest_shop_dsc : desc;

                controlsQuery.mainGrd.grdId.jqGrid('addRowData', $.jgrid.randId(), rowObj);
            }
        },
        //Cancel modify
        f9_func : function(){
            controlsQuery.rawBoxIDInput.val("");

            //UnLock item can't be modify
            controlsQuery.vdrIDSelect.removeAttr("disabled","");
            controlsQuery.rawBoxIDInput.removeAttr("disabled","").removeClass("disabled");
            controlsQuery.woIdSelect.removeAttr("disabled","").removeClass("disabled");

            //Hide f9: cancel modify
            btnQuery.f9.hide();

            //Show other buttons
            btnQuery.f1.show();
            btnQuery.f4.show();
            btnQuery.f8.show();
            btnQuery.f11.show();

            VAL.isModify = false;
            VAL.modifyRowId = -1;

        },
        f11_func : function(){
            var woDialog = new WoDialog();
            woDialog.showDialogFnc();
        },
        cusPrdFunc : function(){
        	var cusPrdDialog = new CusPrdDialog();
        	cusPrdDialog.showDialogFnc();
        },
        addNewMtrlTypeFunc : function(){
            console.debug("In addNewMtrlTypeFunc");
            return false;
        },
        autoCreateBoxFunc : function(){
        	var inTrx, outTrx, keyId;
        	var vdr_id = $.trim(controlsQuery.vdrIDSelect.val());
        	var wo_id = $.trim(controlsQuery.woIdSelect.val());
        	if( !wo_id ){
        		showErrorDialog("","请选择内部订单号！");
        		return false;
        	}
        	if(vdr_id=="098"){
        		keyId = "WZH" + wo_id;
        	}else{
        		keyId = wo_id;
        	}
			inTrx = {
				trx_id : "XPCRTNO",
				action_flg : "B",
				key_id : keyId,
				type : "B"
			};
			outTrx = comTrxSubSendPostJson(inTrx);
			if (outTrx.rtn_code == "0000000") {
				controlsQuery.rawBoxIDInput.val(outTrx.serial_no);
			}
        },
        tmCusPrdFunc : function(){
        	var wo_id = $.trim(controlsQuery.woIdSelect.val());
        	if(!wo_id){
        		showErrorDialog("","请先选择内部订单号！");
        		return false;
        	}
        	var tmCusPrdDialog = new TmCusPrdDialog();
        	tmCusPrdDialog.showDialogFnc();
        }
    };

    /**
     * 客户来料信息
     */
    var CusPrdDialog = function(){

		this.showDialogFnc = function(){
			this.iniDialogFnc();
			var inObj = {
				trx_id : "XPINQCUSPRD",
				action_flg : "Q",
			};
			var outObj = comTrxSubSendPostJson(inObj);
			if (outObj.rtn_code == "0000000") {
				setGridInfo(outObj.table, "#cusPrdGrd");
			}
		};
		this.selectClickFnc = function(){
			var selectedID = $("#cusPrdGrd").jqGrid("getGridParam", "selrow");
			var rowData = $("#cusPrdGrd").jqGrid("getRowData", selectedID);
			controlsQuery.mtrlBoxInput.val(rowData['box_phy_id']);
			controlsQuery.rawBoxIDInput.val(rowData['mtrl_box_id']);
			controlsQuery.rawBoxStdQtyInput.val(rowData['box_capacity']);
			controlsQuery.rawCountInput.val(rowData['block_qty']);
			$('#cusPrdDialog').modal("hide");
		};
		this.iniDialogFnc = function(){
			$("#cusPrdDialog").modal({
				backdrop : true,
				keyboard : false,
				show : false
			});
			$("#cusPrdDialog").unbind('shown.bs.modal');
			$("#cusPrdDialog_selectPrdBtn").unbind('click');

			$('#cusPrdDialog').modal("show");
			$("#cusPrdDialog_selectPrdBtn").bind('click', this.selectClickFnc);
			$("#cusPrdGrd").jqGrid({
                url:"",
                datatype:"local",
                mtype:"POST",
                height:280,
                width:1180,
                shrinkToFit:true,
                scroll:true,
                viewrecords:true,
                rownumbers  :true ,
                rowNum:20,
                rownumWidth : 20,
                resizable : true,
                loadonce:true,
                toppager: true ,
                fixed:true,
                pager : '#cusPrdGrdPg',
                pginput :true,
                fixed: true,
                cellEdit : true,
                cellsubmit : "clientArray",
                emptyrecords :true ,
                colModel:  [
                    {name: 'rcv_timestamp'        , index: 'rcv_timestamp'    , label: RCV_TIMESTAMP_TAG         , width: COM_CLM},
                    {name: 'ope_fab_id'           , index: 'ope_fab_id'       , label: OPE_FAB_ID_TAG            , width: COM_CLM},
                    {name: 'box_phy_id'           , index: 'box_phy_id'       , label: "来料箱代码"             , width: COM_CLM},
                    {name: 'mtrl_box_id'          , index: 'mtrl_box_id'      , label: "来料箱流水码"           , width: COM_CLM},
                    {name: 'cus_group_id'         , index: 'cus_group_id'     , label: "Owner Id"               , width: COM_CLM},
                    {name: 'mtrl_pallet_no'       , index: 'mtrl_pallet_no'   , label: "来料栈板流水码"           , width: COM_CLM},
                    {name: 'mtrl_pallet_id'       , index: 'mtrl_pallet_id'   , label: "来料栈板ID"                , width: COM_CLM},
                    {name: 'mtrl_prod_id_fk'      , index: 'mtrl_prod_id_fk'  , label: MTRL_PROD_ID_TAG          , width: MTRL_PROD_ID_FK_CLM},
                    {name: 'block_size'           , index: 'block_size'       , label: "来料玻璃尺寸 "             , width: SO_ID_CLM},
                    {name: 'part_no'         	  , index: 'part_no'          , label: "来料产品料号"             , width: SO_ID_CLM},
                    {name: 'x_axis_cnt_fk'        , index: 'x_axis_cnt_fk'    , label: "X轴模位数"     , width: COM_CLM},
                    {name: 'y_axis_cnt_fk'        , index: 'y_axis_cnt_fk'    , label: "Y轴模位数"     , width: COM_CLM},
                    {name: 'prd_typ'              , index: 'prd_typ'          , label: "产品类型"      , width: COM_CLM},
                    {name: 'prd_cate'             , index: 'prd_cate'         , label: "产品类别"  , width: COM_CLM},
                    {name: 'box_capacity'         , index: 'box_capacity'     , label: BOX_CAPACITY_TAG          , width: PRD_QTY_CLM},
                    {name: 'block_qty'            , index: 'block_qty'        , label: PRD_QTY_TAG               , width: PRD_QTY_CLM}
                ]
            });
		};
    };
    
    var WoDialog = function(){
        this.showDialogFnc  = function(){
            var iary,
                inTrx,
                outTrx;

            iary = {
                wo_id : controlsQuery.woIdSelect.val()
            };
            inTrx = {
                trx_id     : VAL.T_XPAPLYWO ,
                action_flg : 'Q'        ,
                tbl_cnt    :  1         ,
                iary       :  iary
            };
            outTrx = comTrxSubSendPostJson(inTrx);
            if (outTrx.rtn_code==VAL.NORMAL){
                if( outTrx.tbl_cnt<=0){
                    showErrorDialog("003","此内部订单还没有被创建，请收料后再做绑定");
                    return false;
                }
                if( outTrx.oary.so_id!=undefined){
                    showErrorDialog("003","此内部订单已经绑定过商务订单,不可重复绑定");
                    return false;
                }
                if (baseFnc.returnSpace(controlsQuery.vdrIDSelect.val()) != outTrx.oary.cus_id_fk){
                	showErrorDialog("","当前所选客户["+controlsQuery.vdrIDSelect.val()+"]和内部订单客户["+outTrx.oary.cus_id_fk+"]不符"); 
                	return false;
                }
                if (baseFnc.returnSpace(controlsQuery.mtrlTypeSelect.val()) != outTrx.oary.mtrl_prod_id_fk){
                	showErrorDialog("","当前所选来料型号["+baseFnc.returnSpace(controlsQuery.mtrlTypeSelect.val())+"]和内部订单来料型号["+outTrx.oary.mtrl_prod_id_fk+"]不符"); 
                	return false;
                }
            }

            this.initialDialogFnc();

            iary = {
                mtrl_prod_id : baseFnc.returnSpace(controlsQuery.mtrlTypeSelect.val()),
                cus_id       : baseFnc.returnSpace(controlsQuery.vdrIDSelect.val()),
                wo_cate      : baseFnc.returnSpace(outTrx.oary.wo_cate)
            };
            inTrx = {
                trx_id     : VAL.T_XPAPLYSO,
                action_flg : "S",
                iary       : iary
            };
            outTrx = comTrxSubSendPostJson(inTrx);
            if(outTrx.rtn_code==VAL.NORMAL){
                setGridInfo(outTrx.oary,"#bindWoDialog_woGrd");
            }

        };
        this.bindWoClickFnc = function(){
            var selectRowID,
                iary = new Array(),
                rowData,
                inTrx,
                outTrx,
                woId;

            selectRowID = $("#bindWoDialog_woGrd").jqGrid("getGridParam","selrow");
            if( selectRowID == null || selectRowID ==""){
                showErrorDialog("003","选择需要绑定工单的订单");
                return false;
            }
            woId = $("#bindWODialog_worderIDTxt").val();
            iary={
                wo_id    : woId,
                so_id    : $("#bindWoDialog_woGrd").jqGrid("getRowData",selectRowID).wo_id,
                evt_user : VAL.EVT_USER
            };
            inTrx = {
                trx_id     : VAL.T_XPAPLYSO ,
                action_flg : 'B'        ,
                tbl_cnt    :  1         ,
                iary       :  iary
            };
            outTrx = comTrxSubSendPostJson(inTrx);
            if(outTrx.rtn_code=="0000000"){
                showSuccessDialog("订单绑定成功");
                toolFunc.syncWoSumInfo(woId);
                $('#bindWODialog').modal("hide");
            }
        }
        this.initialDialogFnc = function(){
            $('#bindWODialog').modal({
                backdrop:true,
                keyboard:false,
                show:false
            });
            $('#bindWODialog').unbind('shown.bs.modal');
            $("#bindWODialog_bindWOBtn").unbind('click');

            $('#bindWODialog').modal("show");
            $("#bindWODialog_bindWOBtn").bind('click',this.bindWoClickFnc);
            $("#bindWODialog_worderIDTxt").attr({"disabled":true});
            $("#bindWODialog_worderIDTxt").val(controlsQuery.woIdSelect.val());
            $("#bindWoDialog_woGrd").jqGrid({
                url:"",
                datatype:"local",
                mtype:"POST",
                height:280,
                width:1200,
                shrinkToFit:true,
                scroll:true,
                viewrecords:true,
                rownumbers  :true ,
                rowNum:20,
                rownumWidth : 20,
                resizable : true,
                loadonce:true,
                toppager: true ,
                fixed:true,
                pager : '#bindWoDialog_woPg',
                pginput :true,
                fixed: true,
                cellEdit : true,
                cellsubmit : "clientArray",
                emptyrecords :true ,
                colModel:  [
                    {name: 'wo_id'            , index: 'wo_id'           , label: SO_ID_TAG,          width: WO_ID_CLM},
                    {name: 'wo_cate'          , index: 'wo_cate'         , label: SO_CATE_TAG,        width: WO_CATE_CLM },
                    {name: 'mdl_id'           , index: 'mdl_id'          , label: MDL_ID_TAG,         width: MDL_ID_CLM},
                    {name: 'pln_prd_qty'      , index: 'pln_prd_qty'     , label: EXPECT_COUNT_TAG ,    width: PATH_ID_FK_CLM},
                    {name: 'path_id'          , index: 'path_id'         , label: PATH_ID_TAG,         width: MDL_ID_CLM},
                    {name: 'pln_stb_date'     , index: 'pln_stb_date'    , label: PLAN_FROM_DATE_TAG,   width: PLN_STB_DATE_CLM},
                    {name: 'pln_cmp_date'     , index: 'pln_cmp_date'    , label: PLN_CMP_DATE_TAG,     width: PLN_CMP_DATE_CLM},
                    {name: 'wo_note'          , index: 'wo_note'         , label: ORDER_INSTRUCTION_TAG,    width: WO_NOTE_CLM},
                    {name: 'cus_info_snd'            , index: 'cus_info_snd'           , label: "客户工单号",        width: SO_ID_CLM},
                    {name: 'cus_info_fst'            , index: 'cus_info_fst'           , label: "委外工单号",        width: SO_ID_CLM},
                    {name: 'evt_usr'          , index: 'wo_dsc'          , label: EVT_USR,         width: WO_DSC_CLM},
                    {name: 'evt_timestamp'    , index: 'evt_timestamp'   , label: EVT_TIMESTAMP,         width: EVT_TIMESTAMP_CLM}
                ]
            });
        }
    }
    
    
    $("#tmCusPrdDialog").on("click","#tmCusPrdDialog_cancelBtn",function(){
    	$("#tmCusPrdDialog").modal("hide");
    });
    $("#tmCusPrdDialog").on("click","#tmCusPrdDialog_selectPrdBtn",function(){
    	var selectedID = $("#tmCusPrdGrd").jqGrid("getGridParam", "selrow");
		var rowData = $("#tmCusPrdGrd").jqGrid("getRowData", selectedID);
		if(VAL.woMtrl_Prod_ID.substring(0,9)!=rowData['productspecname'].substring(0,9)){
			 showErrorDialog("003","所选来料箱来料型号和所选工单来料型号不符！");
           return false;
		}
		if(VAL.woMdl_ID.substring(0,9)!=rowData['targetproductspecname'].substring(0,9)){
			 showErrorDialog("003","所选来料箱成品型号和所选工单成品型号不符！");
          return false;
		}
		if(VAL.woCus_Info_Fst!=rowData['targetproductrequest']){
			 showErrorDialog("003","所选来料箱目标工单和所选工单委外工单不符！");
          return false;
		}
		if(VAL.woCus_Info_Snd!=rowData['productrequestname']){
			showErrorDialog("003","所选来料箱工单代码和所选工单客户工单不符！");
	          return false;
		}
		controlsQuery.mtrlBoxInput.val(rowData['boxname']);
		controlsQuery.rawBoxIDInput.val(rowData['boxname']);
		controlsQuery.rawBoxStdQtyInput.val(rowData['boxcapacity']);
		controlsQuery.rawCountInput.val(rowData['productquantity']);
		$('#tmCusPrdDialog').modal("hide");
    });
    
    var TmCusPrdDialog = function(){

		this.showDialogFnc = function(){
			this.iniDialogFnc();
			var inObj = {
				trx_id : "XPINQCUSPRD",
				action_flg : "X",
			};
			var outObj = comTrxSubSendPostJson(inObj);
			if (outObj.rtn_code == "0000000") {
				var oary = outObj.table_tm;
                oary = $.isArray(oary)?oary : [oary.table];
                setGridInfo(oary,"#tmCusPrdGrd");
			}
			$('#tmCusPrdDialog').modal("show");
		};
		this.selectClickFnc = function(){
			
		};
		this.iniDialogFnc = function(){
			$("#tmCusPrdDialog").modal({
				backdrop : true,
				keyboard : false,
				show : false
			});
//			$("#tmCusPrdDialog_selectPrdBtn").bind('click', this.);
			$("#tmCusPrdGrd").jqGrid({
                url:"",
                datatype:"local",
                mtype:"POST",
                height:280,
                width:1180,
                shrinkToFit:true,
                scroll:true,
                viewrecords:true,
                rownumbers  :true ,
                rowNum:20,
                rownumWidth : 20,
                resizable : true,
                loadonce:true,
                toppager: true ,
                fixed:true,
                pager : '#tmCusPrdGrdPg',
                cellEdit : true,
                cellsubmit : "clientArray",
                emptyrecords :true ,
                colModel:  [
                    {name: 'factoryname'           , index: 'factoryname'          , label: "厂别"         , width: COM_CLM},
                    {name: 'productrequestname'    , index: 'productrequestname'   , label: "工单代码"            , width: COM_CLM},
                    {name: 'productspecname'       , index: 'productspecname'      , label: "来料型号"               , width: COM_CLM},
                    {name: 'producttype'           , index: 'producttype'          , label: "产品类型"               , width: COM_CLM},
                    {name: 'thickness'             , index: 'thickness'            , label: "来料厚度"             , width: COM_CLM},
                    {name: 'targetproductspecname' , index: 'targetproductspecname', label: "目标产品规格"                , width: COM_CLM},
                    {name: 'targetproductrequest'  , index: 'targetproductrequest' , label: "目标工单"           , width: COM_CLM},
                    {name: 'targetthickenss'       , index: 'targetthickenss'      , label: "目标厚度"               , width: COM_CLM},
                    {name: 'lotname'               , index: 'lotname'              , label: "批次代码"           , width: MTRL_PROD_ID_FK_CLM},
                    {name: 'boxname'               , index: 'boxname'              , label: "箱号"              , width: SO_ID_CLM},
                    {name: 'boxtype'         	   , index: 'boxtype'              , label: "箱子类型"              , width: SO_ID_CLM},
                    {name: 'boxcapacity'           , index: 'boxcapacity'          , label: "箱子容量"                , width: COM_CLM},
                    {name: 'productquantity'       , index: 'productquantity'      , label: "数量"     , width: COM_CLM},
                    {name: 'eventuser'             , index: 'eventuser'            , label: "操作用户"      , width: COM_CLM},
                    {name: 'eventtime'             , index: 'eventtime'            , label: "操作时间"  , width: COM_CLM}
                ]
            });
		};
    };
    /**
     * Bind button click action
     */
    var iniButtonAction = function(){
        btnQuery.f1.click(function(){
            btnFunc.f1_func();
        });
        btnQuery.f4.click(function(){
            btnFunc.f4_func();
        });
        btnQuery.f5.click(function(){
            btnFunc.f5_func();
        });
        btnQuery.f8.click(function(){
            btnFunc.f8_func();
        });
        btnQuery.f9.click(function(){
            btnFunc.f9_func();
        });
        btnQuery.f11.click(function(){
            btnFunc.f11_func();
        });
//        btnQuery.$importCusPrdBtn.click(function(){
//            btnFunc.cusPrdFunc();
//        });
        btnQuery.addNewMtrlType.click(function(){
            btnFunc.addNewMtrlTypeFunc();
        });
        btnQuery.autoCreateBox.click(function(){
            btnFunc.autoCreateBoxFunc();
        });
        btnQuery.$importTmCusPrdBtn.click(function(){
        	btnFunc.tmCusPrdFunc();
        });
    };

    /**
     * grid  initialization
     */
    var iniGridInfo = function(){
        var grdInfoCM = [
            {name: 'box_id',        index: 'box_id',        label: PPBOX_ID_TAG     , width: BOX_ID_CLM},
            {name: 'vdr_id',        index: 'vdr_id',        label: CUS_ID_TAG       , width: CUS_ID_CLM},
            {name: 'mtrl_type',     index: 'mtrl_type',     label: MTRL_TYPE_TAG    , width: MTRL_PROD_ID_CLM},
            {name: 'dest_shop',     index: 'dest_shop',     label: DEST_SHOP_TAG    , width: DEST_SHOP_CLM ,hidden:true},
            {name: 'dest_shop_dsc', index: 'dest_shop_dsc', label: DEST_SHOP_TAG    , width: DEST_SHOP_CLM },
            {name: 'wo_id',         index: 'wo_id',         label: WO_ID_TAG        , width: WO_ID_CLM},
            {name: 'count',         index: 'count',         label: TOTAL_QTY_TAG    , width: QTY_CLM },
            {name: 'weight',        index: 'weight',        label: WEIGHT_TAG       , width: QTY_CLM },
            {name: 'rcv_user',      index: 'rcv_user',      label: RCV_USER_TAG     , width: USER_CLM},
            {name: 'rcv_timestamp', index: 'rcv_timestamp', label: RCV_TIMESTAMP_TAG, width: TIMESTAMP_CLM},
            {name: 'box_std_qty'   , index: 'box_std_qty'   , label: '', width: 1 , hidden: true},
            {name: 'ppbox_stat'   , index: 'ppbox_stat'   , label: '', width: 1 , hidden: true}
        ];
        controlsQuery.mainGrd.grdId.jqGrid({
            url:"",
            datatype:"local",
            mtype:"POST",
            height:360,
            width:580,
            shrinkToFit:false,
            scroll:true,
            rownumWidth : true,
            resizable : true,
            rowNum:40,
            loadonce:true,
            fixed:true,
            viewrecords:true,
            multiselect : true,
            pager : controlsQuery.mainGrd.grdPgText,
            colModel: grdInfoCM,
            ondblClickRow: function(rowid){
                toolFunc.setRowDateForUpdate(rowid);
            }
        });
    };

    var shortCutKeyBind = function(){
        document.onkeydown = function(event) {
            if(event.keyCode == F1_KEY){
                btnQuery.f1.click();
                return false;
            }else if(event.keyCode == F2_KEY){
                btnQuery.f4.click();
                return false;
            }else if (event.keyCode == F3_KEY) {
                btnQuery.f5.click();
                return false;
            }else if (event.keyCode == F4_KEY) {
                btnQuery.f8.click();
                return false;
            }else if (event.keyCode == F5_KEY) {
                btnQuery.f11.click();
                return false;
            }

            return true;
        };
    };

    /**
     * Other action bind
     */
    var otherActionBind = function(){
        //Stop from auto commit
        $("form").submit(function(){
            return false;
        });

        //Set
        controlsQuery.vdrIDSelect.change(function(){
            setMtrlTypeSelect();
            toolFunc.iniWoIdSelect();
        });
        controlsQuery.mtrlTypeSelect.change(function(){
         
            toolFunc.iniWoIdSelect();
        });
        controlsQuery.woIdSelect.change(function(){
            
            toolFunc.getWoInfo();
        });

        //Auto query when press enter after keyin box ID
        controlsQuery.rawBoxIDInput.keydown(function(event){
            if(event.keyCode === 13){
        		var inObj = {
        				trx_id : "XPINQCUSPRD",
        				action_flg : "B",
        				box_id : controlsQuery.rawBoxIDInput.val()
        			};
        			var outObj = comTrxSubSendPostJson(inObj);
        			if (outObj.rtn_code == "0000000") {
        				controlsQuery.rawBoxStdQtyInput.val(outObj.table_tm.table.boxcapacity);
        				controlsQuery.rawCountInput.val(outObj.table_tm.table.productquantity);
        			}
                btnFunc.f8_func();
            }
        });

        shortCutKeyBind();
    };
//    $("#print_btn").click(function(){
//		  var inObj="",outObj="";
//		  var boxAry = [];
//		  var prdAry =[];
//		  var wo_cnt=0,prdCnt =0,boxRule=0,totalCnt=0;
//		  var i=0,j=0,k=0,p;
//		  var start,left_cnt,right_cnt,end,layout_cnt;
//		  var date = new Date();
//		  var rowData="";
//		  var crGrid = controlsQuery.mainGrd.grdId;
//		  var rowIds = crGrid.jqGrid('getGridParam','selarrrow').concat();
//		  var customer_id ="",mode_name="",str_date="",prod_spec="",
//		  		wo_id="",layout_id="",mtrl_id="",habk_id="";
//		  var len = rowIds.length;
//		  str_date = date.getFullYear() + "-" + ( date.getMonth()+1 ) + "-"+date.getDate();
//		  boxRule = $.trim(controlsQuery.prtBoxRuleInput.val());
//		  totalCnt = $.trim(controlsQuery.woBoxTotalCntInput.val());
//		  mtrl_id = $.trim(controlsQuery.mtrlIdInput.val());
//		  habk_id = $.trim(controlsQuery.hdIdInput.val());
//		  if( rowIds.length == 0){
//			  showErrorDialog("003","请选择需要打印的箱号！");
//	          return false;
//		  }
//		  if( !boxRule ){
//			  showErrorDialog("003","打印标签前，请输入开始打印第几个箱子！");
//	          return false;
//		  }
//		  if( !totalCnt ){
//			  showErrorDialog("003","打印标签前，请输入此订单来料箱子的总数量！");
//	          return false;
//		  }
//		  for( i=0;i<rowIds.length;i++){
//			  var rowData = crGrid.jqGrid('getRowData',rowIds[i]);
//			  boxAry[i] = rowData['box_id'];
//			  prdAry[i] = rowData['count'];
//		  }
//		  wo_id = $.trim( controlsQuery.woIdSelect.val() );
//		  var iary = {
//				  wo_id : wo_id
//		  };
//		  inObj = {
//				trx_id : VAL.T_XPAPLYWO,
//				action_flg : 'Q',
//				iary : iary
//		  };
//		  outObj = comTrxSubSendPostJson( inObj );
//		  customer_id = controlsQuery.vdrIDSelect.val();
//		  mode_name = outObj.oary.mtrl_prod_id_fk;
//		  prod_spec = outObj.oary.mdl_guige;
//		  wo_cnt = outObj.oary.pln_prd_qty;
//		var cus_info_snd = outObj.oary.cus_info_snd;
//		  if(mode_name == null){
//			  showErrorDialog("003","此内部订单没有绑定商务订单！");
//	          return false;
//		  }
//		  /**
//		   * 计算模数layout_cnt
//		   */
//		  layout_id = outObj.oary.layout_id_fk;
//		  for(k=0;k<layout_id.length;k++){
//			  if(layout_id.substring(k, k+1) == '*'){
//				  start = k;
//				  break;
//			  }
//		  }
//		  for(p=start;p<layout_id.length;p++){
//			  if(layout_id.substring(p, p+1)=='_'){
//				  break;
//			  }
//		  }
//		  end = p;
//		  left_cnt = layout_id.substring(0,start);
//		  right_cnt = layout_id.substring(parseInt(start+1,10),end);
//		  layout_cnt = left_cnt * right_cnt;
//		  if( !prod_spec ){
//			  showErrorDialog("003","产品规格没有维护，请确认！");
//	          return false;
//		  }
//		  if(rowData['dest_shop'].substr(0,1)== "D"){
//			  if(mtrl_id == "" || habk_id ==""){
//				  showErrorDialog("003","打印标签前，请输入此订单来料箱子的总数量料号与手册号！");
//		          return false;
//			  }
//		  }
//		  if(cus_info_snd){
//			  customer_id = customer_id+"/"+cus_info_snd;
//		  }
//		  if(rowData['dest_shop'].substr(0,1)== "D"){
//			  label.PrintJX4BS(customer_id,mode_name,str_date,prod_spec,wo_id,wo_cnt,JSON.stringify(prdAry),
//				  		boxRule,totalCnt,JSON.stringify(boxAry),layout_cnt.toString(),mtrl_id,habk_id);
//		  }else{
//			  label.PrintJX(customer_id,mode_name,str_date,prod_spec,wo_id,wo_cnt,JSON.stringify(prdAry),
//				  		boxRule,totalCnt,JSON.stringify(boxAry),layout_cnt.toString());
//		  }
//		  
//		  for(i=0;i<len;i++){
//			  crGrid.jqGrid('delRowData', rowIds[i]);
//		  }
//		  controlsQuery.prtBoxRuleInput.val(parseInt(boxRule,10) + len);
//	  });
    
    //新版打印wfq
//    $("#printNew_btn").click(function(){
//		  var inObj="",outObj="";
//		  var boxAry = [];
//		  var prdAry =[];
//		  var wo_cnt=0,prdCnt =0,boxRule=0,totalCnt=0;
//		  var i=0,j=0,k=0,p;
//		  var start,left_cnt,right_cnt,end,layout_cnt;
//		  var date = new Date();
//		  var rowData="";
//		  var crGrid = controlsQuery.mainGrd.grdId;
//		  var rowIds = crGrid.jqGrid('getGridParam','selarrrow').concat();
//		  var customer_id ="",mode_name="",str_date="",prod_spec="",
//		  		wo_id="",layout_id="",mtrl_id="",habk_id="";
//		  var len = rowIds.length;
//		  str_date = date.getFullYear() + "-" + ( date.getMonth()+1 ) + "-"+date.getDate();
//		  boxRule = $.trim(controlsQuery.prtBoxRuleInput.val());
//		  totalCnt = $.trim(controlsQuery.woBoxTotalCntInput.val());
//		  mtrl_id = $.trim(controlsQuery.mtrlIdInput.val());
//		  habk_id = $.trim(controlsQuery.hdIdInput.val());
//		  if( rowIds.length == 0){
//			  showErrorDialog("003","请选择需要打印的箱号！");
//	          return false;
//		  }
//		  if( !boxRule ){
//			  showErrorDialog("003","打印标签前，请输入开始打印第几个箱子！");
//	          return false;
//		  }
//		  if( !totalCnt ){
//			  showErrorDialog("003","打印标签前，请输入此订单来料箱子的总数量！");
//	          return false;
//		  }
//		  for( i=0;i<rowIds.length;i++){
//			  var rowData = crGrid.jqGrid('getRowData',rowIds[i]);
//			  boxAry[i] = rowData['box_id'];
//			  prdAry[i] = rowData['count'];
//		  }
//		  wo_id = $.trim( controlsQuery.woIdSelect.val() );
//		  var iary = {
//				  wo_id : wo_id
//		  };
//		  inObj = {
//				trx_id : VAL.T_XPAPLYWO,
//				action_flg : 'Q',
//				iary : iary
//		  };
//		  outObj = comTrxSubSendPostJson( inObj );
//		  var iarys = {
//				  wo_id : outObj.oary.so_id,
//				  wo_typ:'S'
//		  };
//		  inObjs = {
//				trx_id : VAL.T_XPAPLYWO,
//				action_flg : 'Q',
//				iary : iarys
//		  };
//		  outObjs = comTrxSubSendPostJson( inObjs );
//		  customer_id = controlsQuery.vdrIDSelect.val();
//		  mode_name = outObj.oary.mtrl_prod_id_fk;
//		  prod_spec = outObj.oary.mdl_guige;
//		  wo_cnt = outObj.oary.pln_prd_qty;
//		  var cuswo = outObjs.oary.cus_info_snd;
//		  if(mode_name == null){
//			  showErrorDialog("003","此内部订单没有绑定商务订单！");
//	          return false;
//		  }
//		  /**
//		   * 计算模数layout_cnt
//		   */
//		  layout_id = outObj.oary.layout_id_fk;
//		  for(k=0;k<layout_id.length;k++){
//			  if(layout_id.substring(k, k+1) == '*'){
//				  start = k;
//				  break;
//			  }
//		  }
//		  for(p=start;p<layout_id.length;p++){
//			  if(layout_id.substring(p, p+1)=='_'){
//				  break;
//			  }
//		  }
//		  end = p;
//		  left_cnt = layout_id.substring(0,start);
//		  right_cnt = layout_id.substring(parseInt(start+1,10),end);
//		  layout_cnt = left_cnt * right_cnt;
//		  if( !prod_spec ){
//			  showErrorDialog("003","产品规格没有维护，请确认！");
//	          return false;
//		  }
//		  if(rowData['dest_shop'].substr(0,1)== "D"){
//			  if(mtrl_id == "" || habk_id ==""){
//				  showErrorDialog("003","打印标签前，请输入此订单来料箱子的总数量料号与手册号！");
//		          return false;
//			  }
//		  }
//		 
//		  label.printyl(customer_id,mode_name,str_date,prod_spec,wo_id,wo_cnt,JSON.stringify(prdAry),
//				  boxRule,totalCnt,JSON.stringify(boxAry),layout_cnt.toString(),mtrl_id,habk_id,cuswo);
//		  
//		  for(i=0;i<len;i++){
//			  crGrid.jqGrid('delRowData', rowIds[i]);
//
//		  }
//		  controlsQuery.prtBoxRuleInput.val(parseInt(boxRule,10) + len);
//	  });
    /**
     * Ini view and data
     */
    var setVdrIDSelect = function(){
        var inTrxObj,
            outTrxObj;

        inTrxObj = {
            trx_id      : 'XPLSTDAT' ,
            action_flg  : 'Q'        ,
            iary        : {
                data_cate : "CUSD"
            }
        };
        outTrxObj = comTrxSubSendPostJson(inTrxObj);
        if( outTrxObj.rtn_code == _NORMAL ) {
            if(1 < parseInt(outTrxObj.tbl_cnt, 10)){
                outTrxObj.oary.sort(function(x, y){
                    if(x.data_item < y.data_item){
                        return -1;
                    }else if(x.data_item > y.data_item){
                        return 1;
                    }else{
                        return 0;
                    }
                });
            }
            _setSelectDate(outTrxObj.tbl_cnt, outTrxObj.oary,
                "data_item", "data_item", "#vdrIDSelect", true);
        }
    };
    var setMtrlTypeSelect = function(){
        "use strict";
        var crSelect = controlsQuery.mtrlTypeSelect,
            vdrID,
            mtrlProdId,
            i,
            tbl_cnt,
            inTrxObj,
            outTrxObj;

        crSelect.empty();
        crSelect.append('<option ></option>');

        vdrID = controlsQuery.vdrIDSelect.val();
        if(!vdrID){
            console.log('客户代码为空。');
            return false;
        }

        inTrxObj = {
            trx_id     : 'XPLSTDAT' ,
            action_flg : 'H' ,
            iary       : {
                data_cate : 'CSMT',
                data_item : vdrID
            }
        };

        outTrxObj = comTrxSubSendPostJson(inTrxObj);
        if( outTrxObj.rtn_code == _NORMAL ) {
            tbl_cnt = parseInt( outTrxObj.tbl_cnt, 10);
            if( tbl_cnt == 1 ){
            	mtrlProdId = outTrxObj.oary['ext_1'];
                crSelect.append('<option value = '+ baseFnc.replaceSpace(mtrlProdId)  +' >'+ mtrlProdId +'</option>');
            }else if(tbl_cnt>1){
                for(i=0;i<tbl_cnt;i++){
                	mtrlProdId = outTrxObj.oary[i]['ext_1'];
                	crSelect.append('<option value = '+ baseFnc.replaceSpace(mtrlProdId)  +'>'+ mtrlProdId +'</option>');
                }
            }
        }

        crSelect.select2({
	    	theme : "bootstrap"
	    });
    };
    var initializationFunc = function(){
        iniGridInfo();
        iniButtonAction();
        otherActionBind();
        
        toolFunc.clearInput();

        //Ini data
        setVdrIDSelect();
        setMtrlTypeSelect();
        toolFunc.setDestShopSel();

        //Wo info
        toolFunc.iniWoIdSelect();

        //Ini view
        btnQuery.f9.hide();
        DestTrans.addTrans("'C','D'");
    };

    initializationFunc();
    function resizeFnc(){                                                                      
    	var offsetBottom, divWidth;                                                              
		                                                                                           
		divWidth = domObj.$panelMaterialDeliveryInfoDiv.width();                                   
		offsetBottom = domObj.$window.height() - domObj.$panelMaterialDeliveryInfoDiv.offset().top;
		domObj.$panelMaterialDeliveryInfoDiv.height(offsetBottom * 0.95);                          
		domObj.$panelMaterialDeliveryInfoGrd.setGridWidth(divWidth * 0.99);                   
		domObj.$panelMaterialDeliveryInfoGrd.setGridHeight(offsetBottom * 0.99 - 51);
		
		domObj.$bindWoDialog_woGrd.setGridWidth(divWidth * 0.85);
    };                                                                                         
    resizeFnc();                                                                               
    domObj.$window.resize(function() {                                                         
    	resizeFnc();                                                                             
	});       
	
});